import 'package:enterprise_v6_app/app/components/special_operation/custom_select_function.dart';
import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/common/personnel_type.dart';
import 'package:enterprise_v6_app/app/data/entities/application/execute_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/change_shifts_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/ticket_plan_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/special_operation/special_list/special_list_controller.dart';
import 'package:enterprise_v6_app/router/app_pages.dart';
import 'package:get/get.dart';

class ChangeShiftsController extends GetxController {
  /// 作业票实体类
  TicketPlanReceiptLists ticketPlanReceiptLists = Get.arguments as TicketPlanReceiptLists;

  /// 当前正在作业的人员
  List<ExecuteTicketReceiptListOperatorLists> currentPersonnel = [];

  /// 当前正在作业的人员根据人员类型分组
  Map<String, List<ExecuteTicketReceiptListOperatorLists>> currentPMap = {};

  /// 选择的交班人分组(默认全部选中)
  Map<String, List<ExecuteTicketReceiptListOperatorLists>> selectedHandoverPersonMap = {};

  /// 选择的接班人根据人员类型分组
  Map<String, List<ExecuteTicketReceiptListOperatorLists>> selectedSuccessorMap = {};

  /// 交接班数据
  List<ChangeShiftsEntity> changeShiftsList = [];

  /// 交接内容
  String handoverContent = '';

  @override
  void onInit() {
    super.onInit();
    // 查询作业人员列表
    _getOperatorList();
  }

  /// 查询作业人员列表
  Future<void> _getOperatorList() async {
    //根据流程唯一编码查询流程详情
    final res = await HttpUtil().generateGetRequest<List<ExecuteTicketReceiptListOperatorLists>>(
        Interface.getOperatorList,
        queryParameters: {'ticketReceiptId': ticketPlanReceiptLists.id}).execute();

    res.onSuccess((result) {
      if (result.data != null) {
        currentPersonnel = result.data!;
        currentPMap.clear();
        // 设置人员类型中文
        for (var item in currentPersonnel) {
          item.operatorName = PersonnelType.getTypeName(
              operatorType: item.operatorType!, ticketBigTypeName: ticketPlanReceiptLists.ticketBigTypeName);
          // 根据类型进行分组
          if (currentPMap[item.operatorName] == null) {
            // 可选择的人员数据
            currentPMap[item.operatorName] = [item.copyWith()];
            // 已选中的人员数据
            selectedHandoverPersonMap[item.operatorName] = [item.copyWith()];
            // 交班人数据
            selectedSuccessorMap[item.operatorName] = [];
          } else {
            currentPMap[item.operatorName]!.add(item.copyWith());
            selectedHandoverPersonMap[item.operatorName]!.add(item.copyWith());
          }
        }
        // 交班人-监护人 去除签名数据
        for (var item in selectedHandoverPersonMap['监护人']!) {
          item.operatorUserSign = '';
        }
        update();
      }
    });
  }

  /// 添加交班人员
  void addHandoverPersonnel(String operatorName, List<ExecuteTicketReceiptListOperatorLists> personnelList) {
    CustomSelectFunction.selectMultipleBottomSheet<ExecuteTicketReceiptListOperatorLists>(
      title: '添加$operatorName',
      dataList: currentPMap[operatorName] ?? [],
      checkedList: personnelList,
      onCallBack: (value) {
        for (var item in value) {
          item.operatorUserSign = '';
        }
        selectedHandoverPersonMap[operatorName] = value;
        update();
      },
    );
  }

  /// 添加接班人员
  /// [displayName] 显示的人员类型名称
  void addSuccessorPersonnel(String displayName) {
    final String operatorName = PersonnelType.getOperatorDisplay(displayName);
    Get.toNamed(AppRoutes.personnelSelection, arguments: {
      'queryParameters': {'roleName': operatorName},
      'isRadio': false,
    })?.then((value) {
      //如果不为空则设置人员信息
      if (value != null) {
        final List<ExecuteTicketReceiptListOperatorLists> successorList = [];
        final List<RolePersonnelEntity> personList = value as List<RolePersonnelEntity>;
        for (var bean in personList) {
          successorList.add(ExecuteTicketReceiptListOperatorLists()
            ..ticketReceiptId = ticketPlanReceiptLists.id
            ..ticketPlanId = ticketPlanReceiptLists.ticketPlanId
            ..number = 1
            ..operatorType = PersonnelType.getOperatorType(name: displayName)
            ..operatorUserName = bean.getShowName()
            ..operatorUserId = bean.getId());
        }
        selectedSuccessorMap[displayName] = successorList;
        update();
      }
    });
  }

  /// 确认
  Future<void> complete() async {
    // 交接内容
    if (handoverContent.isEmpty) {
      AppToast.showWarning('请输入交接内容');
      return;
    }
    // 交班人-监护人
    if (selectedHandoverPersonMap['监护人'] != null) {
      for (var bean in selectedHandoverPersonMap['监护人']!) {
        if (bean.operatorUserSign!.isEmpty) {
          AppToast.showWarning('交班人-监护人请签字!');
          return;
        }
      }
    }
    // 接班人-监护人
    if (selectedSuccessorMap['监护人'] != null) {
      for (var bean in selectedSuccessorMap['监护人']!) {
        if (bean.operatorUserSign!.isEmpty) {
          AppToast.showWarning('接班人-监护人请签字!');
          return;
        }
      }
    }
    // 组装传递数据
    changeShiftsList.clear();
    for (var key in selectedHandoverPersonMap.keys) {
      final value = selectedHandoverPersonMap[key];
      final ChangeShiftsEntity bean = ChangeShiftsEntity();
      // 交接内容
      bean.joinContent = handoverContent;
      // 作业票id
      bean.ticketReceiptId = ticketPlanReceiptLists.id;
      // 作业计划id
      bean.ticketPlanId = ticketPlanReceiptLists.ticketPlanId;
      // 人员类型
      bean.operatorType = PersonnelType.getOperatorType(name: key);
      // 交班人数据
      bean.joinList = value.toString();
      // 接班人数据,如果有交班人则需要选择接班人
      if (value!.isNotEmpty && selectedSuccessorMap[key]!.isEmpty) {
        AppToast.showWarning('接班人-$key请选择!');
        return;
      }
      bean.operatorList = selectedSuccessorMap[key].toString();
      changeShiftsList.add(bean);
    }
    // print(changeShiftsList.toString());
    // 调用交接班接口
    final res = await HttpUtil()
        .generatePostRequest(
          Interface.handover,
          data: changeShiftsList.map((e) => e.toJson()).toList(),
        )
        .execute();
    res.onSuccess((result) {
      uploadOperatorList();
    });
    res.onError((result) {
      AppToast.showWarning('交接失败');
    });
  }

  /// 上传人员作业列表
  Future<void> uploadOperatorList() async {
    // 选择的人员
    final List<ExecuteTicketReceiptListOperatorLists> operatorList = [];
    // 新增所有接班人员信息
    selectedSuccessorMap.forEach((key, value) {
      operatorList.addAll(value);
    });
    final res = await HttpUtil()
        .generatePostRequest(
          Interface.uploadOperatorList,
          data: operatorList.toString(),
        )
        .execute();
    res.onSuccess((result) {
      Get.back();
      Get.back();
      //外部列表controller,刷新列表数据
      final specialListController = Get.find<SpecialListController>();
      specialListController.refreshPage();
      AppToast.showSuccess('交接成功');
    });
    res.onError((result) {
      AppToast.showError('交接失败');
    });
  }
}
